//
//  WHUserAccount.swift
//  microblog
//
//  Created by Apple on 15/11/27.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class WHUserAccount: NSObject,NSCoding {
    
    //用户是否登录
    class var userLogin: Bool {
        get {
            return WHUserAccount.loadUserAccount() == nil
        }
    }
    
    /// 保存过期时间NSDate
    var expiresDate: NSDate?
    //接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            // 设置过期时间
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //当前授权用户的UID。
    var uid: String?
    

    //字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        //KVC 字典转模型
        setValuesForKeysWithDictionary(dict)
    }
    
    // 当字典的key在模型中找不到属性才调用
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    
    }
//    
//    override func setValue(value: AnyObject?, forKey key: String) {
//        
//    }
    
    //定义归档路径
    static let plistPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"    
    //保存账户信息到沙盒
    func saveAccount() {
        //归档当前类
        NSKeyedArchiver.archiveRootObject(self, toFile: WHUserAccount.plistPath)
        
    }
    
    /*
    项目中经常需要使用到CZUserAccount,如果每次调用loadUserAccount,都会去沙盒解档一个账户.这样是比较消耗性能.
    当没有账户,去沙盒解档一个.如果解档账户成功,将它保存在内存中,以后直接访问内存中的账户.可以提高性能
    */
    //内存中的账户
    private static var userAccount: WHUserAccount?
    
    //解档加载账户信息 读取 保存在沙盒里面的账户信息
    class func loadUserAccount() -> WHUserAccount? {
        //// 1.判断内存中的账户是有可用
        if userAccount == nil {
            // 内存中没有账户, 到沙盒加载一个账户(有可能加载出来也有可能加载不出来),赋值给内存中的账户
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(plistPath) as? WHUserAccount
            print("从沙盒加载账户:\(userAccount)")
            }else {
                print("直接从内存中获取到账户")
            }
            // 2.判断内存中是否有用账户,有账户,判断时间是否过期
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            // 有账户并且没有过期,是一个可用的账户
            return userAccount
        }
        return nil
   }

    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
    }
    
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    
    /// 打印对象信息
    override var description: String  {
        let properties = ["access_token" , "expires_in" , "uid"]
        
        return "\(dictionaryWithValuesForKeys(properties))"
        
//        return "access_token: \(access_toKen), expires_in:\(expires_in), uid = \(uid), expiresDate:\(expiresDate)"
    }
    
}
